import time
import simplehtf as htf
from simplehtf.utils import func
import csv

class CMDPlug(htf.BasePlug):
    def setup(self):
        print("[Plug] DUT terminal setup")

    def teardown(self):
        print("[Plug] DUT terminal teardown")

    def run_cmd(self,cmd):
        #假装需要一秒
        time.sleep(1)
        import os
        if cmd == 'uname':
            return 'Darwin'
        return f"{cmd}"


@func.matcher('common_command')
@htf.plug(cmd=CMDPlug)
def common_command_phase(test,cmd,args):
    res = cmd.run_cmd(args)
    print(res)
    return htf.PhaseResult.CONTINUE

@func.matcher('common_command_with_expected_value')
@htf.plug(cmd=CMDPlug)
def common_command_phase(test,cmd,args,expected_value ,mode):
    res = cmd.run_cmd(args)
    print(f"real result is {res}")
    print(f"expected value is {expected_value}")
    if expected_value in res:
        return htf.PhaseResult.CONTINUE
    return 'FAIL'

if __name__ == "__main__":
    func_nodes = []
    with open('./examples/data.csv',mode='r') as f:
        reader = csv.DictReader(f) #以字典方式加载csv文件
        for row in reader:
            if row['matcher'] == 'common_command':
                #把字典中的参数载入到函数生成器
                _func = func.func_generator(
                    row['matcher'],
                    args = row['args'])
            if row['matcher'] == 'common_command_with_expected_value':
                #把字典中的参数载入到函数生成器
                _func = func.func_generator(
                    row['matcher'],
                    args = row['args'],
                    expected_value = row['expected_value'],
                    mode = row['mode'])
            _func.__name__ = row['test_item'] #手动设置测项名字
            #构建一个func列表
            func_nodes.append(_func)

    t = htf.Test(*func_nodes,name = 'MYTEST')
    t.build_phases()
    t.execute()
    record = t.test_record.to_dict()
    import json
    print(json.dumps(record, indent=4, ensure_ascii=False))
    """
    以上代码运行结果
    {
    "metadata": {
        "name": "MYTEST"
    },
    "start_time": 1760878032.61661,
    "end_time": 1760878032.616694,
    "outcome": false,
    "phase_records": [
        {
            "phase_name": "ls_test",
            "start_time": 1760878032.6166122,
            "end_time": 1760878032.616645,
            "outcome": "PASS"
        },
        {
            "phase_name": "uname_command_test",
            "start_time": 1760878032.616647,
            "end_time": 1760878032.616663,
            "outcome": "PASS"
        },
        {
            "phase_name": "system_version_test_1",
            "start_time": 1760878032.6166642,
            "end_time": 1760878032.61668,
            "outcome": "PASS"
        },
        {
            "phase_name": "system_version_test_2",
            "start_time": 1760878032.6166809,
            "end_time": 1760878032.616694,
            "outcome": "FAIL"
        }
    ]
    }
    """